import json
import os
from datetime import datetime
from typing import List, Dict, Any
import logging
logger = logging.getLogger(__name__)


class EventDatabase:
    """事件数据库类，用于直接存储和读取事件处理结果"""

    def __init__(self, db_file="events_db.json"):
        self.db_file = db_file
        self.events = []
        self._ensure_db_file()
        self._load_events()

    def _ensure_db_file(self):
        """确保数据库文件存在"""
        if not os.path.exists(self.db_file):
            with open(self.db_file, 'w') as f:
                json.dump([], f)

    def _load_events(self):
        """从文件加载事件数据"""
        try:
            with open(self.db_file, 'r') as f:
                self.events = json.load(f)
        except (json.JSONDecodeError, FileNotFoundError):
            self.events = []

    def _save_events(self):
        """保存事件数据到文件"""
        with open(self.db_file, 'w') as f:
            json.dump(self.events, f, indent=2)

    def add_event(self, event_data: Dict[str, Any]) -> str:
        """添加新事件到数据库"""
        event_id = f"event_{len(self.events) + 1}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
        event_data['id'] = event_id
        event_data['created_at'] = datetime.now().isoformat()
        self.events.append(event_data)
        self._save_events()
        return event_id

    def get_all_events(self) -> List[Dict[str, Any]]:
        """获取所有事件"""
        return self.events

    def get_event_by_id(self, event_id: str) -> Dict[str, Any]:
        """根据ID获取特定事件"""
        for event in self.events:
            if event.get('id') == event_id:
                return event
        return {}

    def clear_events(self):
        """清空所有事件"""
        self.events = []
        self._save_events()


    @staticmethod
    def format_event_data(db_data):
        """格式化数据库中的原始数据为前端需要的格式"""
        if not db_data:
            return {}

        return {
            "id": db_data.get("id", "N/A"),
            "title": db_data.get("event_info", {}).get("type", "未知事件"),
            "time": db_data.get("timestamp", ""),
            "location": f"({db_data.get('location', {}).get('longitude', 0):.4f}, {db_data.get('location', {}).get('latitude', 0):.4f})",
            "coordinates": [
                db_data.get("location", {}).get("longitude", 0),
                db_data.get("location", {}).get("latitude", 0)
            ],
            "areaType": db_data.get("location", {}).get("area_type", "未知区域"),
            "type": db_data.get("event_info", {}).get("type", "未知类型"),
            "severity": "high" if (db_data.get("event_info", {}).get("severity", 0) > 0.7)
            else "medium" if (db_data.get("event_info", {}).get("severity", 0) > 0.4)
            else "low",
            "confidence": db_data.get("event_info", {}).get("confidence", 0),
            "severityValue": db_data.get("event_info", {}).get("severity", 0),
            "crowdDensity": db_data.get("event_info", {}).get("crowd_density", 0),
            "trafficImpact": db_data.get("predicted_impact", {}).get("traffic_impact", 0),
            "impactDuration": db_data.get("predicted_impact", {}).get("duration", 0),
            "hasInjury": db_data.get("event_info", {}).get("has_injury", False),
            "alertLevel": db_data.get("alert_level", 1),
            "processingOptions": db_data.get("processing_options", []),
            "resourceAllocation": db_data.get("resource_allocation", []),
            "impactMessage": f"交通影响指数: {db_data.get('predicted_impact', {}).get('traffic_impact', 0):.2f}",
            "timeline": db_data.get("timeline", [])
        }

    def save_to_json(self, filename="events_db.json"):
        """将事件数据保存为 JSON 文件"""
        with open(filename, 'w') as f:
            json.dump(self.events, f, indent=2, ensure_ascii=False)
        logger.info(f"事件数据已保存到 {filename}")
# 全局数据库实例
if __name__ == "__main__":
    event_db = EventDatabase()
    event_db.save_to_json()  # 生成 events_db.json